﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LibYanu.Security.Model;
using LibYanu.Security.DTO;
using LibYanu.Security;
using NHibernate.Criterion;
using System.Web.Security;
using log4net;

namespace LibYanu.Web.Provider
{
    public class AplicationOp
    {
        private static ILog log = LogManager.GetLogger(typeof(AplicationOp));
        public AplicationOp()
        {
        }

        public AspnetApplicationDto Create(AspnetApplicationDto mdl)
        {

            using (var ses = new SecurityScope())
            using(var tx= ses.Session.BeginTransaction())
            {
                try
                {
                    var dmn = mdl.ToEntity();
                    ses.Session.Save(dmn);
                    tx.Commit();
                    return dmn.ToDto();
                }
                catch (Exception ex)
                {
                    tx.Rollback();
                    log.Error(ex.Message);
                    
                    
                }

            }
            return null;
        }


        public AspnetApplicationDto getApplicationDtoByName(string ApplicationName, bool createNew)
        {
            AspnetApplicationDto res=getApplicationDtoByName(ApplicationName) ;
            
            if (res == null)
            {             
                if(createNew)
                res = Create(new AspnetApplicationDto() { ApplicationName=ApplicationName,LoweredApplicationName=ApplicationName.ToLower() });                
            }
            return res;         
        }
        
        public AspnetApplicationDto getApplicationDtoByName(string ApplicactionName)
        {
            using (var sc = new SecurityScope())
            {
                try
                {

                    var res = sc.Session.CreateCriteria(typeof(AspnetApplication), "ap")
                               .Add(Expression.Eq("ap.LoweredApplicationName", ApplicactionName.ToLower()))
                               .SetMaxResults(1)
                               .UniqueResult<AspnetApplication>();

                    if (res != null)
                        return res.ToDto();
                    else
                        return null;
                }
                catch (Exception ex)
                {

                    return null;
                }
            }

        }
    }
}
